package com.sharding;

import org.apache.log4j.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 数据源管理类
 * Created by chenjiansheng on 2017-7-25.
 */
public class DataSourceManager {
    private static Logger log = Logger.getLogger(DataSourceManager.class);

    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Map<Object,Object> getDataSourceMap(){
        log.error("getDataSourceMap........................");
        Map<Object,Object> dataSourceMap = new HashMap<Object,Object>();
        try{
            Context context = new InitialContext();
            List<String> list = getDataSourceNameList();
            for(String ds:list){
                dataSourceMap.put(ds,(DataSource)context.lookup("java:comp/env/"+ds));
            }
        }catch(Exception ex){
            log.error("获取数据源出错",ex);
        }
        return dataSourceMap;
    }

    /**
     * 获取数据源名列表
     * @return 数据源名列表
     * @throws Exception
     */
    private List<String> getDataSourceNameList() throws Exception   {
        List<String> list = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet resultSet = null;
        String sSql = "select distinct t.datasource_name from sharding_datasource_cfg t";
        try{
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            log.debug("获取数据源名列表，SQL:"+ sSql);
            stmt.execute(sSql);
            resultSet = stmt.getResultSet();
            while (resultSet.next()){
                list.add(resultSet.getString("datasource_name"));
            }
        }catch(Exception ex){
            log.error("获取数据源名列表失败,SQL:"+sSql,ex);
            list = null;
        }finally {
            if(resultSet!=null){
                resultSet.close();
            }
            if(stmt!=null){
                stmt.close();
            }
            if(conn!=null){
                conn.close();
            }
        }
        return list;
    }
}
